<template>
  <div class="editform">
    <!-- 基本信息 -->
    <div class="duty">公司信息</div>
    <FormPanel ref="FormPanel" :list="formList" :cols="3" labelWidth="120" :formType="type" @formChange="changeHandleFile" :isSubmitBtn="false" ></FormPanel>
    <FilterTable
      height="auto"
      ref="tableInfo"
      :columns="columns"
      :isSelectColumn="false"
      selectionType="single"
      :isMemoryPagination="true"
      :onSyncTableData="syncFun"
      :datakey="'records'"
      :isToperInfo="false"
      :onColumnsChange="columns => (this.columns = columns)"
      columnsRef="notification_maintain_info_02">

      <template slot="controls">
        <el-button v-show=" type == 'add' || type == 'edit'" size="small" type="primary" icon="el-icon-plus" @click="addFun()">新增</el-button>
      </template>
    </FilterTable>
    <div :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'center'
        }">
      <AjaxButton size="small" type="primary" :click="confirmHandle">保存</AjaxButton>
      <el-button size="small" type="primary" @click="closeDialog">返回</el-button>
    </div>
  </div>
</template>

<script>
  import { dictionary } from '@/utils/dictMixin';
  import { region } from '@/api/cms-common/region'; //行政区域
  import { getJsonTree } from '@/utils/index';
  import {doubleCheck} from '@/utils/validate.js';
  import config from '@/assets/js/config';
  import {getComOrgTreeList,getPresetRole} from '@/api/common/org/employeeInfo';
  import {getEmployeeInfo,postEmployeeInfo,} from '@/api/common/auth/employeeAuth'
  import {searchEmployee,} from '@/api/common/auth/dealerStaff';
  import { getCompanyById, insertDealerCompany, updateDealerCompany } from '@/api/common/company/index.js';
  import {phoneAndSolidify,email, companyCode10,systemCode,zipCode,banWord,phone,phoneAndSolidifyNew} from '@/utils/validate.js';
  export default {
    name:'component',
    mixins: [dictionary,region],
    props:['rowData','type'],
    data() {
      return {
        formList: this.createFormList(),
        columns: this.createColumns(),
        imgUrl:null,
        caseUrl: [],
        storePics: [],
        isSelectColumn: false,
        detailData:{}, //修改提交时使用
        saveData: {
          editType: '',
          xxList: []
        }
      };
    },
    mounted () {
      this.init();
      //初始化省份
      this.initProvince();
    },
    methods: {

      createFormList() {
        let bt = { required: true, message: '必填', trigger: ['change', 'blur'] };
        let btl = [bt];
        return [
          {
            type: 'INPUT',
            label: '公司代码',
            fieldName: 'companyCode',
            placeholder: '',
            initialValue: '',
            disabled:this.type === 'edit' ? true : false,
            maxlength: 10,
            rules: [
              bt,
              { validator: companyCode10, trigger: 'blur'}
            ],
          },
          {
            type: 'INPUT',
            label: '公司名称',
            fieldName: 'companyNameCn',
            placeholder: '',
            initialValue: '',
            disabled:this.type === 'edit' ? true : false,
            maxlength: 30,
            rules: btl,
          },
          {
            type: 'INPUT',
            label: '公司简称',
            fieldName: 'companyShortNameCn',
            placeholder: '',
            disabled:this.type === 'edit' ? true : false,
            initialValue: '',
            maxlength: 30,
            rules: btl,
          },
          {
            type: 'INPUT',
            label: '公司名称(英文)',
            fieldName: 'companyNameEn',
            placeholder: '',
            initialValue: '',
            disabled:false,
            maxlength: 30,
            // rules: btl,
          },

          {
            type: 'SELECT',
            label: '省份',
            fieldName: 'provinceId',
            placeholder: '请选择',
            initialValue: '',
            itemList: [],
            rules: btl,
            change: props => {
              this.initCity(props);
            }
          },
          {
            type: 'SELECT',
            label: '城市',
            fieldName: 'cityId',
            placeholder: '请选择',
            initialValue: '',
            itemList: [],
            // rules: btl,
            change: props => this.initTown(props),
            maxlength: 10,
          },
          {
            type: 'SELECT',
            label: '县区',
            fieldName: 'districtId',
            placeholder: '请选择',
            initialValue: '',
            itemList: [],
          },
          {
            type: 'INPUT',
            label: '公司地址',
            fieldName: 'addressCn',
            selfCols: 2,
            rows: 1,
            initialValue: '',
            placeholder: '请输入',
            maxlength: 100,

          },
          {
            type: 'INPUT',
            label: '法人',
            fieldName: 'representative',
            initialValue: '',
            maxlength: 20,
          },
          {
            type: 'INPUT',
            label: '法人联系方式',
            fieldName: 'representativeTel',
            initialValue: '',
            maxlength: 11,
            rules: [
              { validator: phoneAndSolidifyNew, trigger: 'blur'}
            ],
          },
          {
            type: 'INPUT',
            label: '法人邮箱',
            fieldName: 'representativeEmail',
            initialValue: '',
            maxlength: 30,
          },
          {
            type: 'INPUT',
            label: '注册资金（万元）',
            fieldName : 'registeredCapital',
            placeholder: '请输入',
            initialValue: '',
            maxlength: 8,
            rules:[
              { validator: doubleCheck, trigger: 'blur'}
            ]
          },
          {
            type: 'INPUT',
            label: '统一社会信用代码',
            fieldName : 'unifiedSocialCreditCode',
            placeholder: '请输入',
            initialValue: '',
            disabled:this.type === 'edit' ? true : false,
            maxlength: 18,
            rules: [
              bt,
              { validator: systemCode, trigger: 'blur'}
            ]
          },
          {
            type: 'DATE',
            format: 'yyyy-MM-dd',
            dateType: 'exactdate',
            label: '成立时间',
            fieldName : 'establishmentDate',
            placeholder: '请输入',
            initialValue: '',
          },
          {
            type: 'INPUT',
            label: '注册地址',
            fieldName : 'registerAddress',
            placeholder: '请输入',
            selfCols: 2,
            initialValue: '',
            rules: btl,
            maxlength: 100,
          },
          {
            type: 'INPUT',
            label: '邮编',
            fieldName: 'zipCode',
            rows: 1,
            initialValue: '',
            placeholder: '请输入',
            maxlength: 10,
            rules: [
              btl,
              { validator: zipCode, trigger: 'blur'}
              ]

          },
          {
            type: 'INPUT',
            label: '公司E-MAIL',
            fieldName: 'eMail',
            rows: 1,
            initialValue: '',
            placeholder: '请输入',
            maxlength: 50,
          },
          {
            type: 'INPUT',
            label: '企微管理员姓名',
            fieldName : 'weChatName',
            placeholder: '请输入',
            initialValue: '',
            maxlength: 30,
          },
          {
            type: 'INPUT',
            label: '企微管理员手机号',
            fieldName : 'weChatPhone',
            placeholder: '请输入',
            initialValue: '',
            rules: [
              { validator: phoneAndSolidifyNew, trigger: 'blur'}
            ],
            maxlength: 30,
          },
          {
            type: 'INPUT',
            label: '经销商企业微信ID',
            fieldName : 'weChatId',
            placeholder: '请输入',
            initialValue: '',
            selfCols: 2,
            rules: [
              { validator: banWord, trigger: 'blur'}
            ],
            maxlength: 120,
          },
          {
            type: 'SELECT',
            label: '有效状态',
            fieldName: 'validStatus',
            placeholder: '请选择',
            initialValue: '',
            itemList: this.createDictList('1001'),
          },
          {
            type: 'INPUT',
            label: '企微通讯录SECRET',
            fieldName : 'weChatAddress',
            placeholder: '请输入',
            selfCols: 3,
            initialValue: '',
            rules: [
              { validator: banWord, trigger: 'blur'}
            ],
            maxlength: 120,
          },
          {
            type: 'TEXT_AREA',
            label: '公司介绍（描述）',
            fieldName : 'companyDesc',
            placeholder: '请输入',
            selfCols: 3,
            rows: 4,
            initialValue: '',
            rules: btl,
            maxlength: 1000,
          },
          {
            type: 'UPLOAD_FILE',
            label: '附件上传',
            fieldName: 'caseUrl',
            initialValue: [],
            selfCols: 3 ,
            upload: {
              actionUrl: `${config.uploadUrl}/api/file/oss/upload`, // 上传的地址
              limit: 5,
              fileTypes: ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'rar', 'zip', 'txt', 'ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx'],
              max: 1024 * 200
            }
          },
          {
            type: 'UPLOAD_FILE',
            label: '门店图片上传',
            fieldName: 'storePics',
            initialValue: [],
            selfCols: 3 ,
            upload: {
              data:{
                bucketType: 'public'
              },
              actionUrl: `${config.uploadUrl}/api/file/oss/upload`, // 上传的地址
              limit: 1,
              fileSize: 2,
              fileTypes: ['jpg', 'jpeg', 'png', 'bmp'],
              fileRatio: [16,9,1200],
            }
          }
        ];

      },
      //搜索数据
      createColumns(){
        return [
          {
            title: '序号',
            dataIndex: 'index',
            width: 80,
            sorter: true,
            render: props => {
              return <span>{props.$index + 1}</span>;
            }
          },
          {
            title: '操作',
            dataIndex: 'column-action',
            width: 50,
            fixed: 'left',
            hidden: this.type === 'show' ? true : false,
            render: (props, h) => {
              return (
                <div>
                  <el-button v-show={this.type == 'add' || this.type == 'edit'} size="mini" type="text" onClick={() => this.deleteRow(props.row,props.$index)}>
                    删除
                  </el-button>
                </div>
              );
            }
          },
          {
            title: '股权结构名称',
            dataIndex: 'shareholderName',
            filterType: 'input',
            editRequired: false,
            sorter: true,
            editable: true,
            maxlength: 20,
            disabled:this.type === 'show' ? true : false,
          },
          {
            title: '股权结构占比(百分比)',
            dataIndex: 'equityRatio',
            filterType: 'input',
            editRequired: false,
            sorter: true,
            editable: true,
            maxlength: 5,
            disabled:this.type === 'show' ? true : false,
            editValidator:function (val, row, callback){
              if (val === undefined || val === '' || val === null) {
                callback();
              }
              let g = /^([1-9][0-9]*)+(\.[0-9]{1,2})?$/;
              if (g.test(val)) {
                callback();
              }else{
                callback(new Error('只能输入最多带两位小数的数字'));
              }
            },
          },
          {
            title: '股权结构金额(万元)',
            dataIndex: 'inputAmount',
            filterType: 'input',
            editRequired: false,
            sorter: true,
            editable: true,
            maxlength: 15,
            disabled:this.type === 'show' ? true : false,
            editValidator:function (val, row, callback){
              console.log('val',val);
              if (val === undefined || val === '' || val === null) {
                callback();
              }
              let g = /^[0-9]*$/;
              if (g.test(val)) {
                callback();
              }else{
                callback(new Error('只能输入数字'));
              }
            },
            // render: props =>{
            //   return <span> this.props.row.inputAmount.toFixed(2)</span>
            // }
          },
        ];
      },
      syncFun(detail){
        this.saveData.xxList = detail
      },
      addFun(){
        if(this.saveData.xxList.length == 10){
          this.$notify.warning({title: '提示信息',message:'股权结构数量已达到上限'});
          return;
        }
        let p = {
          shareholderName: '',
          equityRatio: '',
          inputAmount: '',
        }
        this.$refs.tableInfo.EXECUTE_INSERT(p)
      },
      deleteRow(row,index) {
        this.$confirm('确认删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$refs.tableInfo.EXECUTE_DELETE([row])
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
      },
      async init(){
        if(this.type == 'add'){
          return ;
        }
        const res = await getCompanyById(this.rowData.companyId);
        let resCopy = JSON.parse(JSON.stringify(res.data));
        this.detailData = resCopy;
        if(res.data.insertEquityList != null){
          this.$refs.tableInfo.EXECUTE_INSERT(res.data.insertEquityList)
        }

        this.formList.forEach(x => {
          //回显数据
          if (resCopy[x.fieldName]) {
            x.initialValue = resCopy[x.fieldName];
          }
        });

        //添加级联下拉选（初始化市，区）
        this.initRegion(resCopy.provinceId, resCopy.cityId);
      },

      //初始化市，区
      initRegion(provinceId, cityId) {
        this.initCity(provinceId, false);
        this.initTown(cityId, false);
      },
      //初始化所在省份
      async initProvince() {
        let pl = await this.createRegionList();
        this.formList.find(item => item.fieldName === 'provinceId').itemList = pl;
      },
      //初始化所在市数据
      async initCity(provinceId, flag = true) {
        if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
          return;
        }
        let city = this.formList.find(item => item.fieldName === 'cityId');
        //清空下级数据
        if (flag) {
          city.initialValue = '';
          let district = this.formList.find(item => item.fieldName === 'districtId');
          district.initialValue = '';
          district.itemList = [];
        }
        //取省数据
        let rd = this.getRegionData();
        this.cityData = rd[provinceId].children;
        let cl = this.createSubRegionList(this.cityData);
        city.itemList = cl;
      },
      //初始化所在县市数据
      async initTown(cityId, flag = true) {
        if (!cityId || cityId == null || typeof cityId == 'undefined') {
          return;
        }
        let district = this.formList.find(item => item.fieldName === 'districtId');
        //清空下级数据
        if (flag) {
          district.initialValue = '';
        }
        let td = this.cityData[cityId].children;
        let tl = this.createSubRegionList(td);
        //部分城市为县级市，没有县区的下级数据
        if (tl.length == 0) {
          // district.rules.required = false;
          district.itemList = [];
          this.$refs.FormPanel.$refs.form.clearValidate();
        } else {
          // district.rules.required = true;
          district.itemList = tl;
        }
      },
      changeHandleFile(data) {
        this.caseUrl = [];
        for (let i = 0; i < data.caseUrl.length; i++) {
          let temp = {};

          temp.url = data.caseUrl[i].url;
          temp.name = data.caseUrl[i].name;

          this.caseUrl.push(temp);
        }
        this.dataInfo = this.caseUrl;
        this.setStorePics(data);

        // if (this.publishType === 'add') {
        //   this.submit();
        // } else if (this.publishType === 'publish') {
        //   this.publish();
        // } else if (this.publishType === 'edit') {
        //   this.update();
        // }
      },
      setStorePics(data){
        this.storePics = [];
        for (let i = 0; i < data.storePics.length; i++) {
          let temp = {};

          temp.url = data.storePics[i].url;
          temp.name = data.storePics[i].name;

          this.storePics.push(temp);
        }
        this.dataInfo = this.storePics;
      },
      async confirmHandle() {
        // let allData = this.getSavingData();
        let allData = this.$refs.FormPanel.SUBMIT_FORM();
        //时间转换
        allData.establishmentDate = this.transTiming(allData.establishmentDate);
        allData.insertEquityList = this.saveData.xxList;
        allData.caseUrl = this.caseUrl;
        allData.storePics = this.storePics;
        let flag = true;
        const error = this.$refs.tableInfo.GET_FORMAT_ERROR() // 正则的判断
        console.log(error)
        if (error) {
          flag = false;
          this.$notify.error({title: '提示信息',message:'验证有误，请检查数据格式和必填项!'});
        }
        await this.$refs.FormPanel.$refs.form.validate().catch(err => {
          flag = false;
        });
        if(!flag){
          return;
        }

        let res = {};
        if(this.type == 'add'){
          res = await insertDealerCompany(allData);
        }else if(this.type == 'edit'){
          res = await updateDealerCompany(this.detailData.companyId, allData);
        }
        if(res.resultCode == 200){
          this.closeDialog('refresh');
        }
      },

      transTiming(value){
        console.log("timing orgin value:",value);
        let regex = /^[1-2][0-9][0-9][0-9]-([1][0-2]|0?[1-9])-([12][0-9]|3[01]|0?[1-9])$/;
        let regex2 = /^[1-2][0-9][0-9][0-9]-([1][0-2]|0?[1-9])-([12][0-9]|3[01]|0?[1-9]) ([01]?[0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$/;
        if (regex.test(value)) {
          value = value + " 00:00:00";
        }else if(regex2.test(value)){
          value = value;
        }else{
          value = value;
        }
        return value;
      },

      /**
       * 获取待提交数据
       * @returns {*|{}}
       */

      getSavingData(){
        //股权结构

        // allData.logisticsList = this.saveData.xxList;
        allData.insertEquityList = this.$refs.tableInfo.GET_INSERT_ROWS();
        return allData;
      },

      // 返回
      closeDialog(type) {
        this.$emit('close', type);
      },

    },
  };
</script>

<style lang="less" scoped>
  .clearfix::after {
    content: '';
    height: 0;
    visibility: hidden;
    clear: both;
    display: block;
  }
  .clearfix {
    zoom: 1;
  }
  .editform{
    .FormPanelDiv{
      width: 80%;
      float: left;
      margin-right: 3%;
    }
    .imgDiv{
      width: 12%;
      // min-height: 150px;
      border: 1px solid #000;
      float: left;
      /* position: absolute;
      right: 10%;
      top: 0; */
    }
    .editformBtn{
      text-align: center;
      margin-top: 15px;
    }
    .duty{
      width: 99%;
      height: 30px;
      line-height: 30px;
      margin-bottom: 5px;
      background: #eee;
      text-indent: 5px;
    }
  }

</style>
